package com.itheima.project.config;

import com.itheima.project.core.enums.search.SearchEnum;
import com.itheima.project.exception.ProjectException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
/**
 * ES远程对象 转换器
 * 用于将 原生API对象 转 json
 *          json     转 原生API对象
 */
@Component
public class DelegateEsConfigParser {
    @Autowired
    private NamedXContentRegistry contentRegistry;
    /**
     * 将搜索条件builder对象 转为 json字符串
     * @param sourceBuilder
     * @return
     */
    public String toString(SearchSourceBuilder sourceBuilder){
        return Strings.toString(sourceBuilder);
    }
    /**
     * 将搜索条件json字符串  转为  builder对象
     * @param searchContent
     * @return
     */
    public SearchSourceBuilder parseSearchSourceBuilder(String searchContent){
        XContentParser parser = null;
        try {
            parser = XContentType.JSON.xContent().createParser(contentRegistry,
                    LoggingDeprecationHandler.INSTANCE,
                    searchContent);
            return SearchSourceBuilder.fromXContent(parser);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ProjectException(SearchEnum.DOCUMENT_SEARCH_FAIL,"json转换原生API对象失败");
        }
    }

    /**
     * 将原生结果对象  转为  json
     * @param response
     * @return
     */
    public String toString(SearchResponse response){
        return Strings.toString(response);
    }

    /**
     * 将搜索条件json字符串  转为  searchResponse 对象
     * @param responseContent
     * @return
     */
    public SearchResponse parseSearchResponse(String responseContent){
        XContentParser parser = null;
        try {
            parser = XContentType.JSON.xContent().createParser(contentRegistry,
                    LoggingDeprecationHandler.INSTANCE,
                    responseContent);
            return SearchResponse.fromXContent(parser);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ProjectException(SearchEnum.DOCUMENT_SEARCH_FAIL,"json转换原生API对象失败");
        }
    }
}
